How would I import a module within an npm package

2019-04-18 15:31发布

问题:

Lets say theres a package in node_modules called foo and I want to import a module within a library such as foo/module via webpack & babel...

import Foo from 'foo'; works

import SomeOtherModule from 'foo/module'; fails with the following:

Module not found: Error: Cannot resolve module 'foo/module' in /Users/x/Desktop/someproject/js

Which makes make it seem like webpack is looking for the file in the wrong place instead of node_modules

My webpack.config looks like this:

var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: ['babel-polyfill','./js/script.js'],
    output: {
        path: __dirname,
        filename: './build/script.js'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel',
                query: {
                    cacheDirectory: true,
                    presets: ['es2015']
                }
            }
        ],
    },
    plugins: [
        new webpack.NoErrorsPlugin()
    ],
    stats: {
        colors: true
    },
    devtool: 'source-map'

};

回答1:

It should work with import 'foo/module';. It will resolve file ./node_modules/foo/module.js or ./node_modules/foo/module/index.js and not something like ./node_modules/foo/node_modules/module/index.js if it expected (in that case you better to install module via npm).